import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-ruku-create-dialog',
  templateUrl: './ruku-create-dialog.component.html',
  styleUrls: ['./ruku-create-dialog.component.scss'],
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, FormsModule]
})
export class RukuCreateDialogComponent {
  @Input() visible = false;
  @Output() close = new EventEmitter<void>();
  @Output() save = new EventEmitter<any>();

  form: FormGroup;
  imagePreview: string | ArrayBuffer | null = null;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      ruKuNo: [''],
      ruKuType: ['', Validators.required],
      ruKuStatus: ['', Validators.required],
      ruKuDate: [''],
      storehouseName: ['', Validators.required],
      connectNo: [''],
      itemName: [''],
      attnName: [''],
      ruKuNum: [''],
      ruKuPrice: [''],
      departName: [''],
      shenName: [''],
      shenDate: [''],
      provider: [''],
      phoneName: [''],
      phoneNum: [''],
      remark: [''],
      picture: [null],
      details: this.fb.array([])
    });
  }

  get details() {
    return this.form.get('details') as FormArray;
  }

  addDetail() {
    this.details.push(this.fb.group({
      itemName: ['', Validators.required],
      goodsType: [''],
      goodsSpec: [''],
      unit: [''],
      currentNum: [''],
      purchaseNum: [''],
      yiRuNum: [''],
      weiRuNum: [''],
      purchasePrice: [''],
      purchaseJine: [''],
      ruLocation: [''],
      benRuNum: [''],
      piCiNo: [''],
      createdate: [''],
      remarks: [''],
      ruKuType: ['']
    }));
  }

  removeDetail(i: number) {
    this.details.removeAt(i);
  }

  handleFileInput(event: any) {
    const file = event.target.files[0];
    if (file) {
      this.form.patchValue({ picture: file });
      const reader = new FileReader();
      reader.onload = e => this.imagePreview = reader.result;
      reader.readAsDataURL(file);
    }
  }

  onClose() {
    this.close.emit();
  }

  onSave() {
    if (!this.form.value.ruKuNo) {
      // 自动生成唯一入库单号（如RK20240709123045）
      const now = new Date();
      const pad = (n: number) => n.toString().padStart(2, '0');
      const dateStr = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`;
      const timeStr = `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
      this.form.patchValue({ ruKuNo: `RK${dateStr}${timeStr}` });
    }
    if (this.form.valid) {
      this.save.emit(this.form.value);
    } else {
      this.form.markAllAsTouched();
    }
  }
} 